package com.how.diaryfriend.data;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class DiaryRepository {
    private LiveData<List<Diary>> allDiaryLive;
    private DiaryDao diaryDao;

    public DiaryRepository(Context context) {
        DiaryDatabase wordDatabase = DiaryDatabase.getDatabase(context.getApplicationContext());
        diaryDao = wordDatabase.getDiaryDao();
        allDiaryLive = diaryDao.selectAll();
    }

    public void insertDiary(Diary... Diary) {
        new InsertAsyncTask(diaryDao).execute(Diary);
    }

    public void updateDiary(Diary... Diary) {
        new UpdateAsyncTask(diaryDao).execute(Diary);
    }

    public void deleteDiary(Diary... Diary) {
        new DeleteAsyncTask(diaryDao).execute(Diary);
    }


    public   LiveData<List<Diary>> getAllDiaryLive() {
        return allDiaryLive;
    }

    static class InsertAsyncTask extends AsyncTask<Diary, Void, Void> {
        private DiaryDao wordDao;

        InsertAsyncTask(DiaryDao wordDao) {
            this.wordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Diary... diary) {
            wordDao.insertDiary(diary);
            return null;
        }

    }

    static class UpdateAsyncTask extends AsyncTask<Diary, Void, Void> {
        private DiaryDao diaryDao;

        UpdateAsyncTask(DiaryDao diaryDao) {
            this.diaryDao = diaryDao;
        }

        @Override
        protected Void doInBackground(Diary... diary) {
            diaryDao.updateDiary(diary);
            return null;
        }

    }

    static class DeleteAsyncTask extends AsyncTask<Diary, Void, Void> {
        private DiaryDao wordDao;

        DeleteAsyncTask(DiaryDao wordDao) {
            this.wordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Diary... diaries) {
            wordDao.deleteDiary(diaries);
            return null;
        }

    }

    static class DeleteAllAsyncTask extends AsyncTask<Diary, Void, Void> {
        private DiaryDao wordDao;

        DeleteAllAsyncTask(DiaryDao wordDao) {
            this.wordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Diary... diaries) {
            wordDao.deleteDiary(diaries);
            return null;
        }

    }

}
